#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 04-Nov-09 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

using Thn;
#endregion

namespace Thn.Interface.Vcl
{
    /// <summary>
    /// The most popular control. No comment is neccessary ;-)
    /// </summary>
    [ToolboxItem(true)
    , DefaultProperty("Text")
    , DefaultEvent("Click")
    , ToolboxBitmap(typeof(ResourceBeacon), "Thn.Interface.Vcl.Resources.Icons.Button.bmp")]
#if DEBUG
    public
#else
    public
#endif
 class Button : ControlBase, IButtonControl
    {
        #region Fields
        #endregion

        #region Properties

        #region Alignment
        private ContentAlignment mAlignment = ContentAlignment.MiddleCenter;
        /// <summary>
        /// Gets or Sets alignment of content.
        /// </summary>
        [Browsable(true), DefaultValue(ContentAlignment.MiddleCenter), Category("Appearance"), Description("How to arrange contents")]
        public ContentAlignment Alignment
        {
            get { return mAlignment; }
            set
            {
                if (mAlignment != value)
                {
                    mAlignment = value;
                    InvalidateLayout();
                }
            }
        }
        #endregion

        #region Icon
        private Image mIcon;
        /// <summary>
        /// Gets/Sets the icon to represent this button.
        /// </summary>
        [Browsable(true), DefaultValue(null), Category("Appearance"), Description("Image to quickly regconize this button")]
        public Image Icon
        {
            get { return mIcon; }
            set
            {
                mIcon = value;
                mIconStyle = IconStyle.Custom;
                ApplyIconStyle();
                InvalidateLayout();
            }
        }
        #endregion

        #region Icon Style
        private IconStyle mIconStyle = IconStyle.Custom;
        /// <summary>
        /// Gets/Sets the pre-defined icon styles.
        /// </summary>
        [Browsable(true), DefaultValue(IconStyle.Custom), Category("Appearance"), Description("Pre-defined icon style")]
        public IconStyle IconStyle
        {
            get { return mIconStyle; }
            set
            {
                mIconStyle = value;
                ApplyIconStyle();
                InvalidateLayout();
            }
        }

        /// <summary>
        /// Apply the selected icon 
        /// </summary>
        protected virtual void ApplyIconStyle()
        {
            if (mIconStyle == IconStyle.Custom)
            {
                mRenderContext.Icon = mIcon;
            }
            else
            {
                mRenderContext.Icon = EffectiveTheme.FindImage(string.Format("{0}", mIconStyle));
            }
        }
        #endregion

        #region Text Style
        private TextStyle mTextStyle = TextStyle.Normal;
        /// <summary>
        /// Gets/Sets font style for rendering text.
        /// </summary>
        [Browsable(true), DefaultValue(TextStyle.Normal), Category("Appearance"), Description("Font style for rendering text")]
        public TextStyle TextStyle
        {
            get { return mTextStyle; }
            set
            {
                mTextStyle = value;
                Invalidate();
            }
        }
        #endregion

        #region Render Context
        private ButtonRenderContext mRenderContext = new ButtonRenderContext();
        /// <summary>
        /// Gets reference to current renderation context.
        /// </summary>
        protected ButtonRenderContext RenderContext
        {
            get { return mRenderContext; }
        }
        #endregion

        #endregion

        #region Depress Button
        /// <summary>
        /// Switch to pressed state
        /// </summary>
        void DepressButton()
        {
            if (Enabled)
            {
                if (mRenderContext.State != ButtonState.Pressed)
                {
                    mRenderContext.State = ButtonState.Pressed;
                    Invalidate();
                }
                #region Defensive tracing
                else
                {
                    //not interested in other state
                }
                #endregion
            }
            #region Defensive tracing
            else
            {
                //currently disabled, no need to handle anything
            }
            #endregion
        }
        #endregion

        #region Release Button
        void ReleaseButton()
        {
            if (Enabled)
            {
                if (mRenderContext.State == ButtonState.Pressed)
                {
                    mRenderContext.State = ButtonState.Over;
                    Invalidate();
                }
                #region Defensive tracing
                else
                {
                    //not interested in other state
                }
                #endregion
            }
            #region Defensive tracing
            else
            {
                //currently disabled, no need to handle anything
            }
            #endregion
        }
        #endregion

        #region On Get Render Context
        /// <summary>
        /// Get reference to the renderation context which is used by <see cref="IControlRenderer"/>.
        /// </summary>
        protected override RenderContext OnGetRenderContext(Graphics canvas)
        {
            //get icon
            if (mIconStyle == IconStyle.Custom)
            {
                mRenderContext.Icon = mIcon;
            }
            else
            {
                //mRenderContext.Icon = U
            }

            return mRenderContext;
        }
        #endregion

        #region On Calculate Layout
        /// <summary>
        /// Perform layout calculations neccessary for this control.
        /// </summary>
        protected override void OnCalculateLayout()
        {
            Image img = mRenderContext.Icon;

            Rectangle rControl = this.ClientRectangle;
            rControl.Inflate(-2, -2);
            ////Rectangle r = this.ClientRectangle;
            ////int m = 10;
            ////rControl = new Rectangle(r.Left + m, r.Top + 4, r.Width - m * 2, r.Height - m * 2);

            int imgSize = rControl.Height;
            if (rControl.Width < imgSize) imgSize = rControl.Width;

            int pad = (int)(imgSize * 0.1);
            int mCornerRadius = 5;
            imgSize = imgSize - pad - mCornerRadius / 2;

            Rectangle rImage = Rectangle.Empty;
            if (img == null) rImage.Size = new Size(0, 0);
            else rImage.Size = new Size(imgSize, imgSize);

            rImage.Location = new Point(rControl.Left + mCornerRadius, rControl.Top + pad);
            mRenderContext.IconRegion = rImage;
            mRenderContext.TextRegion = new Rectangle(rImage.Right, rControl.Top + pad, rControl.Right - rImage.Right - mCornerRadius, rControl.Height - pad * 2);
        }
        #endregion

        #region On Click
        protected override void OnClick(EventArgs e)
        {
            //set focus to this control if not focused yet
            if (!Focused) Focus();
            #region Defensive tracing
            else
            {
                //already focused
            }
            #endregion

            base.OnClick(e);
        }
        #endregion

        #region Mouse Events

        #region On Mouse Enter
        protected override void OnMouseEnter(EventArgs e)
        {
            if (Enabled)
            {
                if (mRenderContext.State == ButtonState.Normal)
                {
                    mRenderContext.State = ButtonState.Over;
                    Invalidate();
                }
                #region Defensive tracing
                else
                {
                    //not interested in other state
                }
                #endregion
            }
            #region Defensive tracing
            else
            {
                //currently disabled, no need to handle anything
            }
            #endregion

            base.OnMouseEnter(e);
        }
        #endregion

        #region On Mouse Leave
        protected override void OnMouseLeave(EventArgs e)
        {
            if (Enabled)
            {                
                if (mRenderContext.State == ButtonState.Over)
                {
                    mRenderContext.State = ButtonState.Normal;
                    Invalidate();
                }
                #region Defensive tracing
                else
                {
                    //not interested in other state
                }
                #endregion
            }
            #region Defensive tracing
            else
            {
                //currently disabled, no need to handle anything
            }
            #endregion

            base.OnMouseLeave(e);
        }
        #endregion

        #region On Mouse Down
        protected override void OnMouseDown(MouseEventArgs e)
        {
            DepressButton();

            base.OnMouseDown(e);
        }
        #endregion

        #region On Mouse Up
        protected override void OnMouseUp(MouseEventArgs e)
        {
            ReleaseButton();

            base.OnMouseUp(e);
        }
        #endregion

        #endregion

        #region Keyboard Events

        #region On Key Down
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Space) || (e.KeyCode == Keys.Enter))
            {
                DepressButton();
            }
            #region Defensive tracing
            else
            {
                //not interested in other keys
                base.OnKeyDown(e);
            }
            #endregion

            base.OnKeyDown(e);
        }
        #endregion

        #region On Key Up
        protected override void OnKeyUp(KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Space) || (e.KeyCode == Keys.Enter))
            {
                ReleaseButton();
                OnClick(EventArgs.Empty);
            }
            #region Defensive tracing
            else
            {
                //not interested in other keys
                base.OnKeyUp(e);
            }
            #endregion

            base.OnKeyUp(e);
        }
        #endregion

        #endregion

        #region On Enabled Changed
        protected override void OnEnabledChanged(EventArgs e)
        {
            mRenderContext.State = ButtonState.Normal;
            base.OnEnabledChanged(e);
        }
        #endregion

        #region On Lost Focus
        protected override void OnLostFocus(EventArgs e)
        {
            mRenderContext.State = ButtonState.Normal;
            base.OnLostFocus(e);
            Invalidate();
        }
        #endregion

        #region IButtonControl Members

        #region Dialog Result
        private DialogResult mDialogResult = DialogResult.None;
        /// <summary>
        /// Gets/Sets DialogResult
        /// </summary>
        [Browsable(true), DefaultValue(DialogResult.None), Category("Behavior")]
        public DialogResult DialogResult
        {
            get { return mDialogResult; }
            set
            {
                if (Enum.IsDefined(typeof(DialogResult), value))
                {
                    mDialogResult = value;
                }
            }
        }
        #endregion

        #region Is Default
        private bool mIsDefault = false;
        /// <summary>
        /// Gets/Sets whether this button is the default button of form
        /// </summary>
        [Browsable(true), DefaultValue(false), Category("Behavior")]
        public bool IsDefault
        {
            get { return mIsDefault; }
            set { mIsDefault = value; }
        }
        #endregion

        #region Notify Default
        void IButtonControl.NotifyDefault(bool value)
        {
            if (this.IsDefault != value)
            {
                this.IsDefault = value;
            }

        }
        #endregion

        #region Perform Click
        void IButtonControl.PerformClick()
        {
            if (this.CanSelect)
            {
                this.OnClick(EventArgs.Empty);
            }
        }
        #endregion

        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public Button()
        {
            this.Size = new Size(75, 23);
            //mTransparencyMethod = TransparencyMethod.TransparentWindows;
            mRenderContext = new ButtonRenderContext();
        }
        #endregion
    }
}
